#!/usr/bin/python 
#Author:eager.yu
#Email: sanguren@qq.com
from Cloudstack_option import Cloudstack_option
import sys,re
import getopt


def usage():
    print "this scipt used for get the instance status"
    print "python check_instance_status.py -i cda17664-ae40-4a4a-9ca9-d3b0081109a7"
    print  "get all instances status"
    print  "python check_instance_status.py -l true"
    print "end---------------------------------------------------------------------"

def main():
    id=""
    listall=""
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:l:",["help", "id=","listall="])
    except getopt.GetoptError as err:
        print str(err) 
        usage()
        sys.exit(2)
    for o,a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif o in ("-i", "--id"):
            id=a
        elif o in ("-l", "--listall"):
            listall=a
        else:
            assert False, "unhandled option"
            
    cs=Cloudstack_option()
    instances=cs.get_all_instance("")
    if id != "" :
        
        instances_id=[]
        for i in range(len(instances)):
            instances_id.append(instances[i]["id"])
        if not id in instances_id:
            print "the instance is not  in cloudstack"
            sys.exit()
        args={"id":id}
        req=cs.get_instance(args)
    
        print "%s:%s    %s:%s    %s:%s " % ("instance_name",req['name'],
                                   "ipaddress",req['ipaddress'],
                                   "status",req['status'])
        sys.exit(0)
    elif id == "" and listall != "true":
        print "id can't be null"
        sys.exit()
    elif listall == "true":
        for i in instances:
            print "%s:%s    %s:%s    %s:%s " % ("instance_name",i['name'],
                                   "ipaddress",i["nic"][0]["ipaddress"],
                                   "status",i['state'])
    sys.exit(0)


if __name__ == "__main__":
    main()